<?php

namespace app\common\model;

use think\Model;

/**
 * 配置模型
 */
class Something extends Model
{

    // 表名,不含前缀
    protected $name = 'something';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    // 定义时间戳字段名
    protected $createTime = false;
    // 追加属性
    protected $append = [
    ];

    /**
     * 关联获取用户信息
     */
    public function user(){
        return $this->belongsTo('user','publisherUserId','id',[],'LEFT')->setEagerlyType(0);
    }


    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s',$value);
    }
    public function getUpdatetimeAttr($value)
    {
        if(!empty($value)){
            return date('Y-m-d H:i:s',$value);
        }else{
            return date('Y-m-d H:i:s',time());
        }

    }




    /**
     * @param $id   用户id
     * @return array返回数组
     */
    public function getUser($id){
       try{
           $userModel =new User();
           $user=$userModel->where(['id'=>array('eq',$id)])->find();
           $user=$user->toArray();
       }catch (\Exception $e){
           return [];
       }
        return $user;
    }

    /**
     * @param $page 页码
     * @param int $limit 加载条数
     * @return array 返回数组
     */
    public function getListNew($where,$page,$limit=10,$city){
       try{
           $site=\think\Config::get('site');
           if(empty($where)){
               $where=1;
           }

           $data=$this
               ->where($where)
               ->where("if(cycle=1,date_add(from_unixtime(something.createtime, '%Y-%m-%d %H:%i:%S'), interval 30 day)>now(),something.createtime>0) ")
               ->where(" if(something.type=2,something.city>=0,something.city=".$city.") ")
               ->with('user')
               ->page($page)
               ->order("something.createtime desc")
               ->limit($limit)
               ->select();


           foreach ($data as $row) {
               $row->visible(['id','content','images','contacts','receiverUserId','updatetime','publisherUserId','money','eurekaContent','eurekaimages','cycle','status','type','detailedaddress','browse','createtime']);
               $row->visible(['user']);
               $row->getRelation('user')->visible(['username','nickname','avatar']);
           }
           if(!empty($data)){
               $data=collection($data)->toArray();
               foreach ($data as $key=>$val){
                   $data[$key]['detailedaddress']=cut_str($val['detailedaddress'],40,'...');
                   if($val['type']==1){
                       if(!empty($site['completed_revenue'])&&$site['completed_revenue']>0){
                          if($site['completed_revenue']>100){
                              $site['completed_revenue']=100;
                          }
                           $data[$key]['partake']=$val['money']*(1-$site['completed_revenue']/100)/100;

                       }else{
                           $data[$key]['partake']=0;
                       }

                   }elseif($val['type']==2||$val['type']==3){

                       if(!empty($site['share_profit'])&&$site['share_profit']>0){
                           if($site['share_profit']>100){
                               $site['share_profit']=100;
                           }
                           $data[$key]['partake']=$val['money']*(1-$site['share_profit']/100)/100;

                       }else{
                           $data[$key]['partake']=0;
                       }

                   }

                   $data[$key]['imageslist']=explode(',',$val['images']);
                   if(!empty($val['eurekaimages'])){
                       $data[$key]['eurekaimageslist']=explode(',',$val['eurekaimages']);
                   }else{
                       $data[$key]['eurekaimageslist']=[];
                   }
                   $data[$key]['url']=url('index/detail',array('id'=>$val['id']));

                   if($val['type']==1){
                       $data[$key]['label']='失物招领';
                       $data[$key]['q_name']='报酬';
                   }elseif ($val['type']==2){
                       $data[$key]['q_name']='赏金';
                       $data[$key]['label']='找人';
                   }elseif ($val['type']==3){
                       $data[$key]['label']='找物';
                       $data[$key]['q_name']='赏金';
                   }

                   if($val['status']==1){
                       $data[$key]['status_name']='进行中';
                   }elseif ($val['status']==2){
                       $data[$key]['status_name']='确认中';
                   }elseif ($val['status']==3){
                       $data[$key]['status_name']='已找到';
                   }elseif ($val['status']==4){
                       $data[$key]['status_name']='已结束';
                   }elseif ($val['status']==5){
                       $data[$key]['status_name']='已关闭';
                   }elseif ($val['status']==6){
                       $data[$key]['status_name']='拒绝';
                   }elseif ($val['status']==7){
                       $data[$key]['status_name']='已退款';
                   }elseif ($val['status']==0){
                       $data[$key]['status_name']='未支付';
                   }
                   $data[$key]['receiverUser']=User::get($val['receiverUserId']);
                   if(empty($data[$key]['receiverUser'])){
                       $data[$key]['receiverUser']['avatar']='';
                       $data[$key]['receiverUser']['nickname']='';
                   }
                   if($val['cycle']==1){
                       $date1 =$val['createtime'];
                       $data[$key]['deadline']=date('Y-m-d',strtotime("$date1 +30 day"));
                   }elseif ($val['cycle']==2){
                       $data[$key]['deadline']='永久';
                   }

               }
           }else{
               $data=[];
           }
       }catch (\Exception $e){
           $data=[];
       }
       return $data;
    }

    /**
     * @param $page 页码
     * @param int $limit 加载条数
     * @return array 返回数组
     */
    public function getList($where,$page,$limit=10){
        try{
            $site=\think\Config::get('site');
            if(empty($where)){
                $where=1;
            }

            $data=$this
                ->where($where)
                ->where("if(cycle=1,date_add(from_unixtime(something.createtime, '%Y-%m-%d %H:%i:%S'), interval 30 day)>now(),something.createtime>0) ")
                ->with('user')
                ->page($page)
                ->order("something.createtime desc")
                ->limit($limit)
                ->select();


            foreach ($data as $row) {
                $row->visible(['id','content','images','contacts','receiverUserId','updatetime','publisherUserId','money','eurekaContent','eurekaimages','cycle','status','type','detailedaddress','browse','createtime']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username','nickname','avatar']);
            }
            if(!empty($data)){
                $data=collection($data)->toArray();
                foreach ($data as $key=>$val){
                    $data[$key]['detailedaddress']=cut_str($val['detailedaddress'],40,'...');
                    if($val['type']==1){
                        if(!empty($site['completed_revenue'])&&$site['completed_revenue']>0){
                            if($site['completed_revenue']>100){
                                $site['completed_revenue']=100;
                            }
                            $data[$key]['partake']=$val['money']*(1-$site['completed_revenue']/100)/100;

                        }else{
                            $data[$key]['partake']=0;
                        }

                    }elseif($val['type']==2||$val['type']==3){

                        if(!empty($site['share_profit'])&&$site['share_profit']>0){
                            if($site['share_profit']>100){
                                $site['share_profit']=100;
                            }
                            $data[$key]['partake']=$val['money']*(1-$site['share_profit']/100)/100;

                        }else{
                            $data[$key]['partake']=0;
                        }

                    }

                    $data[$key]['imageslist']=explode(',',$val['images']);
                    if(!empty($val['eurekaimages'])){
                        $data[$key]['eurekaimageslist']=explode(',',$val['eurekaimages']);
                    }else{
                        $data[$key]['eurekaimageslist']=[];
                    }
                    $data[$key]['url']=url('index/detail',array('id'=>$val['id']));

                    if($val['type']==1){
                        $data[$key]['label']='失物招领';
                        $data[$key]['q_name']='报酬';
                    }elseif ($val['type']==2){
                        $data[$key]['q_name']='赏金';
                        $data[$key]['label']='找人';
                    }elseif ($val['type']==3){
                        $data[$key]['label']='找物';
                        $data[$key]['q_name']='赏金';
                    }

                    if($val['status']==1){
                        $data[$key]['status_name']='进行中';
                    }elseif ($val['status']==2){
                        $data[$key]['status_name']='确认中';
                    }elseif ($val['status']==3){
                        $data[$key]['status_name']='已找到';
                    }elseif ($val['status']==4){
                        $data[$key]['status_name']='已结束';
                    }elseif ($val['status']==5){
                        $data[$key]['status_name']='已关闭';
                    }elseif ($val['status']==6){
                        $data[$key]['status_name']='拒绝';
                    }elseif ($val['status']==7){
                        $data[$key]['status_name']='已退款';
                    }elseif ($val['status']==0){
                        $data[$key]['status_name']='未支付';
                    }
                    $data[$key]['receiverUser']=User::get($val['receiverUserId']);
                    if(empty($data[$key]['receiverUser'])){
                        $data[$key]['receiverUser']['avatar']='';
                        $data[$key]['receiverUser']['nickname']='';
                    }
                    if($val['cycle']==1){
                        $date1 =$val['createtime'];
                        $data[$key]['deadline']=date('Y-m-d',strtotime("$date1 +30 day"));
                    }elseif ($val['cycle']==2){
                        $data[$key]['deadline']='永久';
                    }

                }
            }else{
                $data=[];
            }
        }catch (\Exception $e){
            $data=[];
        }
        return $data;
    }


    /**
     * @param $page 页码
     * @param int $limit 加载条数
     * @return array 返回数组
     */
    public function nearby($where,$page,$limit=10,$longitude,$latitude,$city){
        try{
            $site=\think\Config::get('site');
            if(empty($where)){
                $where=1;
            }

//            $field = "something.longitude,something.latitude";
            $field = '( 6371.137 * acos (cos(radians('.$latitude.'))*cos(radians( something.latitude ))*cos( radians(something.longitude )-radians('.$longitude.'))+sin(radians('.$latitude.'))*sin(radians(something.latitude)))) AS distance';


            $data=$this
                ->where($where)
                ->where("if(cycle=1,date_add(from_unixtime(something.createtime, '%Y-%m-%d %H:%i:%S'), interval 30 day)>now(),something.createtime>0) ")
                ->where(" if(something.type=2,something.city>=0,something.city=".$city.") ")
                ->with('user')
                ->field($field)
                ->order('distance')
                ->page($page)
                ->limit($limit)
                ->select();

            foreach ($data as $row) {
                $row->visible(['id','content','contacts','images','publisherUserId','money','status','type','detailedaddress','browse','createtime']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username','nickname','avatar']);
            }
            if(!empty($data)){
                $data=collection($data)->toArray();
                foreach ($data as $key=>$val){
                    $data[$key]['detailedaddress']=cut_str($val['detailedaddress'],40,'...');
                    if($val['type']==1){
                        if(!empty($site['completed_revenue'])&&$site['completed_revenue']>0){
                            if($site['completed_revenue']>100){
                                $site['completed_revenue']=100;
                            }
                            $data[$key]['partake']=$val['money']*(1-$site['completed_revenue']/100)/100;

                        }else{
                            $data[$key]['partake']=0;
                        }

                    }elseif($val['type']==2||$val['type']==3){

                        if(!empty($site['share_profit'])&&$site['share_profit']>0){
                            if($site['share_profit']>100){
                                $site['share_profit']=100;
                            }
                            $data[$key]['partake']=$val['money']*(1-$site['share_profit']/100)/100;

                        }else{
                            $data[$key]['partake']=0;
                        }

                    }

                    $data[$key]['imageslist']=explode(',',$val['images']);
                    if(!empty($val['eurekaimages'])){
                        $data[$key]['eurekaimageslist']=explode(',',$val['eurekaimages']);
                    }else{
                        $data[$key]['eurekaimageslist']='';
                    }
                    $data[$key]['url']=url('index/detail',array('id'=>$val['id']));
                    if($val['type']==1){
                        $data[$key]['label']='失物招领';
                    }elseif ($val['type']==2){
                        $data[$key]['label']='找人';
                    }elseif ($val['type']==3){
                        $data[$key]['label']='找物';
                    }
                }
            }else{
                $data=[];
            }
        }catch (\Exception $e){
            $data=[];
        }
        return $data;
    }




    /**
     * @param $data 要更新数据
     * @param $id   更新id
     * @return bool 返回true或false
     */
    public function InsertSome($data,$id){
        try{
            $this->save($data,['id'=>$id]);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /**
     * @param $data 需插入收
     * @return bool 返回插入是否成功
     */
    public function InsertData($data){
        try{
            $id=$this->insertGetId($data);
        }catch (\Exception $e){
            return $e->getMessage();
        }
        return $id;
    }

    /**
     * 状态更新
     * @param $data
     * @param $id
     * @return bool
     */
    public function UpdateDelay($data,$id){
        try{
            $this->where(['id'=>array('eq',$id)])->update($data);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }



}
